import * as menuService from '../services/system/MenuService';
import * as userService from '../services/system/UserService';
import { judgePermission,isloadPermission,setPermission } from '../common/shiro';
import { Constants } from '../common/constant/constants';
export default {
  namespace: 'menu',

  state: {
    loading:false,
    menuTree:[],
    permission:{
    },
  },

  effects: {
    *fetch(_, { call, put }) {
      yield put({
        type: 'changeLoading',
        payload: true,
      });
      const response = yield call(menuService.getMenuTree);
      yield put({
        type: 'saveTree',
        payload: response.result,
      });
      return response;
    },
    *delete({ payload }, { call, put }) {
      yield put({
        type: 'changeLoading',
        payload: true,
      });
      const response = yield call(menuService.deleteMenu,payload);
      yield put({
        type: 'changeLoading',
        payload: false,
      });
      return response;
    },
    *post({ payload }, { call, put }){
      yield put({
        type: 'changeLoading',
        payload: true,
      });
      let response;
      payload.menuId = parseInt(payload.menuId);
      if(payload.menuId==0){//新建
        response = yield call(menuService.saveMenu,payload);
      }else{//修改   
        response = yield call(menuService.updateMenu,payload);
      }
      yield put({
        type: 'changeLoading',
        payload: false,
      });
      return response;      
    },

    *judgePermission(_, { call, put }){
      if(!isloadPermission()){
        const response = yield call(userService.getPermissions);
        setPermission(response.result)
      }
      var permission = judgePermission(Constants.SYSTEM_MENU.PERM);
      yield put({
        type: 'savePermission',
        payload:permission,
      });
      return permission;
    },
  },

  reducers: {
    changeLoading(state, { payload }) {
      return {
        ...state,
        loading: payload,
      }
    },
    savePermission(state,{payload}){
      return {
        ...state,
        permission:payload,
      }
    },
    saveTree(state, { payload }) {
      return {
        ...state,
        loading:false,
        menuTree: payload,
      };
    },
  },
};
